package com.sgb.kjwl.view.ui.activity.pick;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.KeyboardUtils;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityPickSreachBinding;
import com.sgb.kjwl.di.pick.DaggerPickComponent;
import com.sgb.kjwl.di.pick.PickModule;
import com.sgb.kjwl.model.entity.pick.PickSearchResult;
import com.sgb.kjwl.model.entity.pick.PickSearchType;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.PickEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.adapter.pick.PickSearchResultAdapter;
import com.sgb.kjwl.view.ui.fragment.pick.DemandSearchListFragment;
import com.sgb.kjwl.view.ui.fragment.pick.PickBiddingListFragment;
import com.sgb.kjwl.view.ui.fragment.pick.PickCompanyListFragment;
import com.sgb.kjwl.view.ui.fragment.pick.PickNoticingBidFragment;
import com.sgb.kjwl.view.ui.fragment.pick.PickSigningUpListFragment;
import com.sgb.kjwl.viewmodel.pick.PickSearchModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ResolutionUtil;
import com.swgk.core.util.SharedPreferenceUtil;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

/**
 * 招采大搜索
 */
public class PickSearchActivity extends AppActivity {
    private ActivityPickSreachBinding binding;
    String searchText = "";
    boolean isSearching = false; //是否执行搜索
    boolean isClick = false; //是否点击联想词
    int position = 0; //当前界面的下标
    private ArrayList<Fragment> mFragments;

    @Inject
    PickSearchModel pickSearchModel;
    private SlidingFragmentPagerAdapter pagerAdapter;

    private PickSigningUpListFragment pickSigningUpListFragment;
    private PickBiddingListFragment pickBiddingListFragment;

    private List<String> searchList = new ArrayList<>();
    private Gson gson;
    private PickSearchResultAdapter pickSearchResultAdapter;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, PickSearchActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPickComponent.builder()
                .appComponent(appComponent)
                .pickModule(new PickModule(PickSearchActivity.this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(PickSearchActivity.this, R.layout.activity_pick_sreach);
        gson = GsonManager.getInstance().getGson();

        getData();

        binding.topLayout.etView.setTextColor(getResources().getColor(R.color.color_tab_one));
        binding.topLayout.etView.setHint("输入关键词搜索");
        binding.topLayout.etView.setBackground(getResources().getDrawable(R.drawable.search_round_bg));
        binding.topLayout.ivBack.setOnClickListener(this);
        binding.topLayout.tvSearch.setOnClickListener(this);
        binding.topLayout.tvSearchDelete.setOnClickListener(this);
        binding.imgBackTop.setOnClickListener(this);
        binding.searchDelete.setOnClickListener(this);
        binding.topLayout.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.topLayout.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (isSearching) return true;
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (TextUtils.isEmpty(binding.topLayout.etView.getText().toString())) {
                        MToast.showToast(PickSearchActivity.this, "请输入搜索内容");
                        return true;
                    }
//                    if (searchText.equals(binding.topLayout.etView.getText().toString())){
//                        MToast.showToast(PickSearchActivity.this, "请输入不同的搜索内容");
//                        return true;
//                    }
                    isSearching = true;
                    searchText = binding.topLayout.etView.getText().toString().trim();
                    doSearch();
                }
                return false;
            }
        });
        KeyboardUtils.hideSoftInput(this);
        binding.topLayout.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                binding.searchData.setVisibility(View.GONE);
                if (pickSearchResultAdapter.getCount() == 0) {
                    binding.searchLine.setVisibility(View.VISIBLE);
                } else {
                    binding.searchListResult.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    binding.topLayout.tvSearchDelete.setVisibility(View.GONE);
                } else {
                    binding.topLayout.tvSearchDelete.setVisibility(View.VISIBLE);
                    if(!isClick){
                        pickSearchModel.findListSearch(s.toString());
                    }
                }
            }
        });
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(binding.topLayout.etView, 0);
                           }
                       },
                200);

        binding.topLayout.etView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                EventBus.getDefault().postSticky(PickEvent.make().setMessageTag(EventConstant.EVENT_PICK_SIGNING_FOCUS).setMessageData(hasFocus));
            }
        });

        binding.topLayout.etView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.topLayout.etView.requestFocus();
                binding.topLayout.etView.setSelection(binding.topLayout.etView.getText().length());
                binding.searchData.setVisibility(View.GONE);
            }
        });

        pickSearchResultAdapter = new PickSearchResultAdapter(this, null);
        pickSearchResultAdapter.setOnItemClick(new AdapterOnItemClick<PickSearchResult>() {
            @Override
            public void onItemClick(PickSearchResult pickSearchResult, int position) {
                isClick = true;
                binding.topLayout.etView.setCursorVisible(false);
                binding.topLayout.etView.setText(pickSearchResult.getTitle());

                binding.searchLine.setVisibility(View.GONE);
                binding.searchListResult.setVisibility(View.GONE);
                pickSearchModel.findMenuList(pickSearchResult.getTitle());

                if (!searchList.contains(pickSearchResult.getTitle())) {
                    searchList.add(0, pickSearchResult.getTitle());
                    if (searchList.size() > 10) {
                        searchList.remove((searchList.size() - 1));
                    }
                    SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.PICK_SEARCH, gson.toJson(searchList));
                }
            }
        });
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_list_divide1));
        binding.searchListResult.addItemDecoration(divider);
        binding.searchListResult.setLayoutManager(new LinearLayoutManager(this));
        binding.searchListResult.setAdapter(pickSearchResultAdapter);
    }

    private void doSearch() {
        pickSearchModel.findMenuList(searchText);

        if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            //未登录
            addHistoryWord(searchText);
        } else {
            //登录
            pickSearchModel.addSearchRecord(searchText);
        }
    }

    private void getData() {
        PermissionsUtil.requestPermission(PickSearchActivity.this, new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permissions) {
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //未登录
                    getHistoryWord();
                } else {
                    //登录
                    pickSearchModel.findListBySearchName(searchText);
                }
            }

            @Override
            public void permissionDenied(@NonNull String[] permissions) {
                MToast.showLongToast(getActivity(), "请先获取读写权限");
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 搜索出来的总数据
     *
     * @param data
     */
    public void showfindMenu(PickSearchType data, String keyword) {
        searchText = keyword;
        isSearching = false;
        isClick = false;
        binding.topLayout.etView.setCursorVisible(true);
        binding.topLayout.etView.setSelection(binding.topLayout.etView.getText().length());
        position = 0;
        List<String> titleList = new ArrayList<>();
        titleList.add("招标(" + data.getTenderCount() + ")");
        titleList.add("竞价(" + data.getBidCount() + ")");
        titleList.add("需求预告(" + data.getDemandNoticeCount() + ")");
        titleList.add("中标公告(" + data.getBidNoticeCount() + ")");
        titleList.add("招采企业(" + data.getEnterpriseCount() + ")");
        binding.emptyView.setVisibility(View.GONE);
        binding.searchLine.setVisibility(View.GONE);
        binding.searchListResult.setVisibility(View.GONE);
        binding.searchData.setVisibility(View.VISIBLE);

        int num = titleList.size();
        mFragments = new ArrayList<>();
        String[] titles = new String[num];
        for (int i = 0; i < num; i++) {
            titles[i] = titleList.get(i);
            if (i == 0) {
                mFragments.add(PickSigningUpListFragment.newInstance(keyword, data.getTenderCount()));
            } else if (i == 1) {
                mFragments.add(PickBiddingListFragment.newInstance(keyword, data.getBidCount()));
            } else if (i == 2) {
                mFragments.add(DemandSearchListFragment.newInstance(keyword));
            } else if (i == 3) {
                mFragments.add(PickNoticingBidFragment.newInstance(keyword, data.getBidNoticeCount()));
            } else if (i == 4) {
                mFragments.add(PickCompanyListFragment.newInstance(keyword, data.getEnterpriseCount()));
            }
        }
        if (pagerAdapter != null) {
            pagerAdapter.setFragments(mFragments, titles);
        } else {
            pagerAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, titles);
        }

        binding.viewPager.setAdapter(pagerAdapter);
        binding.viewPager.setCurrentItem(position);
        binding.viewPager.setOffscreenPageLimit(mFragments.size());

        pickSigningUpListFragment = (PickSigningUpListFragment) mFragments.get(0);
        pickBiddingListFragment = (PickBiddingListFragment) mFragments.get(1);

    }

    @Override
    protected void init() {
        binding.tablayout.setupWithViewPager(binding.viewPager);
        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {
                position = i;
                EventBus.getDefault().postSticky(PickEvent.make().setMessageTag(EventConstant.EVENT_PICK_SIGNING_POPUPWINDOW).setMessageData(position));
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search_delete:
                isSearching = false;
                binding.topLayout.etView.setText("");
                searchText = "";
                if (pagerAdapter == null) {
                    pagerAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), new ArrayList<>(), new String[]{});
                }else{
                    pagerAdapter.setFragments(new ArrayList<>(), new String[]{});
                }
                position = 0;
                getData();
                break;
            case R.id.tv_search:
                if (isSearching) return;
                if (TextUtils.isEmpty(binding.topLayout.etView.getText().toString())) {
                    MToast.showToast(PickSearchActivity.this, "请输入搜索内容");
                    return;
                }
//                if (searchText.equals(binding.topLayout.etView.getText().toString())){
//                    MToast.showToast(PickSearchActivity.this, "请输入不同的搜索内容");
//                    return;
//                }
                searchText = binding.topLayout.etView.getText().toString().trim();
                doSearch();
                break;
            case R.id.img_back_top:
                int position = binding.viewPager.getCurrentItem();
                switch (position) {
                    case 0:
                        pickSigningUpListFragment.fullScroll();
                        break;
                    case 1:
                        pickBiddingListFragment.fullScroll();
                        break;
                    case 2:
                        PickNoticingBidFragment pickNoticingBidFragment = (PickNoticingBidFragment) mFragments.get(2);
                        pickNoticingBidFragment.fullScroll();
                        break;
                    case 3:
                        DemandSearchListFragment DemandSearchListFragment = (DemandSearchListFragment) mFragments.get(3);
                        DemandSearchListFragment.fullScroll();
                        break;
                    case 4:
                        PickCompanyListFragment pickCompanyListFragment = (PickCompanyListFragment) mFragments.get(4);
                        pickCompanyListFragment.fullScroll();
                        break;
                }
                break;
            case R.id.search_delete:
                showDeleteDialog();
                break;
        }
    }

    //删除确认框
    public void showDeleteDialog() {
        View view = View.inflate(this, R.layout.dialog_two_btn_del, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        TextView tv_cancel = view.findViewById(R.id.tv_cancel);

        //确定
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_confirm.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                tv_cancel.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                roundCornerDialog.dismiss();
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.searchData.setVisibility(View.GONE);
                binding.searchLine.setVisibility(View.GONE);
                binding.searchListResult.setVisibility(View.GONE);

                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //未登录
                    SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.PICK_SEARCH, "");
                    searchList.clear();
                } else {
                    //登录
                    pickSearchModel.deleteUserAllRecord();
                }

            }
        });

        //取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_cancel.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                tv_confirm.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                roundCornerDialog.dismiss();
            }
        });
    }

    /**
     * 将搜索词汇记录在本地
     */
    private void addHistoryWord(String newWords) {

        PermissionsUtil.requestPermission(PickSearchActivity.this, new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permissions) {
                String historyWords = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.PICK_SEARCH, "");
                if (historyWords != "" && historyWords != null) {
                    searchList = gson.fromJson(historyWords, new TypeToken<List<String>>() {
                    }.getType());

                }

                if (!searchList.contains(newWords)) {
                    searchList.add(0, newWords);
                    if (searchList.size() > 10) {
                        searchList.remove((searchList.size() - 1));
                    }
                    SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.PICK_SEARCH, gson.toJson(searchList));
                }
            }

            @Override
            public void permissionDenied(@NonNull String[] permissions) {
                MToast.showLongToast(getActivity(), "请先获取读写权限");
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }

    /**
     * 获取本地搜索词汇
     */
    private void getHistoryWord() {
        String historyWords = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.PICK_SEARCH, "");
        if (TextUtils.isEmpty(historyWords)) {
            binding.searchLine.setVisibility(View.GONE);
            binding.emptyView.setVisibility(View.VISIBLE);
        } else {
            showData(gson.fromJson(historyWords, new TypeToken<List<String>>() {
            }.getType()));
        }
    }

    public void showData(List<String> stringList) {

        if (stringList == null || stringList.size() == 0) {
            binding.emptyView.setVisibility(View.VISIBLE);
            binding.searchLine.setVisibility(View.GONE);
            binding.searchData.setVisibility(View.GONE);
            binding.searchListResult.setVisibility(View.GONE);
            return;
        }

        binding.emptyView.setVisibility(View.GONE);
        binding.searchLine.setVisibility(View.VISIBLE);
        binding.searchListResult.setVisibility(View.GONE);
        binding.searchData.setVisibility(View.GONE);

        final LayoutInflater mInflater = LayoutInflater.from(PickSearchActivity.this);
        TagAdapter searchAdapter = new TagAdapter<String>(stringList) {
            @Override
            public View getView(com.zhy.view.flowlayout.FlowLayout parent, int position, String s) {
                LinearLayout layout = (LinearLayout) mInflater.inflate(R.layout.item_jicai_search_words, binding.searchList, false);
                TextView tv = layout.findViewById(R.id.name);
                int width = ResolutionUtil.getScreenWidth(PickSearchActivity.this) - ResolutionUtil.dp2px(getActivity(), 75);
                tv.setWidth(width / 4);
                tv.setText(s);
                return layout;
            }
        };
        binding.searchList.setAdapter(searchAdapter);
        binding.searchList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, com.zhy.view.flowlayout.FlowLayout parent) {
                String s = stringList.get(position);
                isClick = true;
                binding.topLayout.etView.setCursorVisible(false);
                binding.topLayout.etView.setText(s);

                binding.searchLine.setVisibility(View.GONE);
                binding.searchListResult.setVisibility(View.GONE);
                pickSearchModel.findMenuList(s);

                stringList.remove(position);
                stringList.add(0, s);
                SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.PICK_SEARCH, gson.toJson(stringList));
                return false;
            }
        });
    }

    public void showSearchData(List<PickSearchResult> stringList) {
        isClick = false;
        binding.topLayout.etView.setCursorVisible(true);
        binding.topLayout.etView.setSelection(binding.topLayout.etView.getText().length());

        if (stringList != null && stringList.size() > 0) {
            binding.searchListResult.setVisibility(View.VISIBLE);
            binding.searchLine.setVisibility(View.GONE);
            if (stringList.size() > 10) {
                stringList = stringList.subList(0, 9);
            }
            pickSearchResultAdapter.setSelectedText(binding.topLayout.etView.getText().toString());
            pickSearchResultAdapter.setDatas(stringList);
            binding.searchListResult.setAdapter(pickSearchResultAdapter);
        } else {
            binding.searchListResult.setVisibility(View.GONE);
            if (searchList.size() == 0) {
                binding.searchLine.setVisibility(View.GONE);
            } else {
                binding.searchLine.setVisibility(View.VISIBLE);
            }
            pickSearchResultAdapter.setDatas(new ArrayList<>());
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data == null) {
                return;
            }
            double latitude = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            double longitude = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
            int isFragment = data.getIntExtra(SelectAddressActivity.IS_FRAGMENT, 0);

            //通知下层界面
            if (isFragment == 255) {   //招标
                EventBus.getDefault().postSticky(PickEvent.make().setMessageTag(EventConstant.EVENT_PICK_SIGNING_DATA_UPDATA).setMessageData(address, latitude, longitude));
            }

            if (isFragment == 256) {  //竞价
                EventBus.getDefault().postSticky(PickEvent.make().setMessageTag(EventConstant.EVENT_PICK_BIDDING_DATA_UPDATA).setMessageData(address, latitude, longitude));
            }

        }
    }

    public void showTopBack(boolean isMap) {
        if (isMap) {
            binding.imgBackTop.setVisibility(View.GONE);
        } else {
            binding.imgBackTop.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 判断当前界面为某个fragment
     *
     * @return
     */
    public boolean isShow(String type) {
        if (type.equals("招标")) {
            return binding.viewPager.getCurrentItem() == 0;
        } else if (type.equals("竞价")) {
            return binding.viewPager.getCurrentItem() == 1;
        }
        return false;
    }

}
